package com.taiji.dianthus.dao.sms;

import com.taiji.dianthus.domain.sms.SmsAccount;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @InterfaceName SmsGroupRepository
 * @Description
 * @Author H.M
 * @Date 2020/7/15
 */
@Repository
public interface SmsAccountRepository extends JpaRepository<SmsAccount, String>,
        JpaSpecificationExecutor<SmsAccount> {


    /*数据库目前有两个短信账号  本系统暂时使用最新账号 对外调用使用旧账号*/
    @Query(value = "select t.* from t_sms_account t where t.enable_flag=1 and t.sign='zmyw4WnbV' and t.is_out_call=0 and (t.use_time <=:time  or t.use_time is null) ", nativeQuery = true)
    List<SmsAccount> getInvalidBackAccount(Pageable pageable, @Param("time") Date time);

    //TODO 对外调用短信接口 对外调用使用新账号  加上时间判断
    @Query(value = "select t.* from t_sms_account t where  t.enable_flag=1 and t.is_out_call=1 and t.sign='zmyw4WnbV' and (t.use_time <=:time  or t.use_time is null) ", nativeQuery = true)
    List<SmsAccount> getInvalidBackAccountOutCall(Pageable pageable, @Param("time") Date time);

   /* @Query("select t from SmsAccount t where  t.enableFlag=1 and t.isOutCall=1 and t.sign='guFS7Ibfh'")
    List<SmsAccount> getInvalidBackAccountOutCall(Pageable pageable, @Param("time") Date time);*/

    @Query("select t from SmsAccount t where  t.enableFlag=1 and t.addSerial=:addSerial")
    SmsAccount getIdByMobile(@Param("addSerial") String addSerial);

    @Modifying
    @Transactional
    @Query("update SmsAccount set useTime=:date where id=:id")
    void updateUseTimeById(@Param("id") String id, @Param("date") Date date);

    @Modifying
    @Transactional
    @Query("update SmsAccount set enableFlag=0 where id=:id")
    void updateFlag(@Param("id") String id);

    @Query("select t from SmsAccount t where  t.enableFlag=1 and t.baseNumber=:baseNumber and t.extendNumber=:extendNumber")
    List<SmsAccount> getByAppNameByAdd(@Param("baseNumber") String baseNumber, @Param("extendNumber") String extendNumber);

    @Query("select t from SmsAccount t where  t.enableFlag=1 and t.baseNumber=:baseNumber and t.extendNumber=:extendNumber and t.id <>:id")
    List<SmsAccount> getByAppNameByEdit(@Param("baseNumber") String baseNumber, @Param("extendNumber") String extendNumber, @Param("id") String id);


}
